package pers.litao.bit.gateway.fifter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import pers.litao.bit.commons.utils.Constant;
import pers.litao.bit.commons.utils.JwtUtil;
import pers.litao.bit.commons.utils.R;
import pers.litao.bit.commons.utils.SysUtil;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 *请求拦截
 */
@Component
@ConfigurationProperties("url-filter")
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private  List<String> jwtExcludePath ;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        R r = new R();

        //2. 则获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 如果是登录请求则放行
       //System.out.println(request.getURI().getPath());

        for(String url : jwtExcludePath){
           if(url.charAt(url.length() - 1) != '}'){
               if(request.getURI().getPath().equals(url)){
                   return chain.filter(exchange);
               }
           }
           else {
               String u1 = url.substring(0,url.indexOf("{") - 1);
               String u2 = request.getURI().getPath().substring(0,request.getURI().getPath().lastIndexOf("/"));
               String i1 = request.getURI().getPath().substring(request.getURI().getPath().lastIndexOf("/") + 1);
               if(u2.equals(u1) && (SysUtil.isNumber(i1) || SysUtil.isPhone(i1))){
                   return chain.filter(exchange);
               }
           }
        }
        //4. 获取请求头
        HttpHeaders headers = request.getHeaders();
        //5. 请求头中获取令牌
        String token = headers.getFirst("token");
        //6. 判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)) {
            log.error("请求路径" +request.getURI().getPath() + "被拦截,原因是没有TOKEN");
            r.put("code", Constant.ResponseCode.NOT_TOKEN.getCode());
            r.put("msg",Constant.ResponseCode.NOT_TOKEN.getMsg());
            JSONObject message = new JSONObject(r);
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        //9. 如果请求头中有令牌则解析令牌
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            log.error("请求路径" +request.getURI().getPath() + "被拦截,原因是TOKEN验证失效");
            r.put("code", Constant.ResponseCode.TOKEM_INVALID.getCode());
            r.put("msg",Constant.ResponseCode.TOKEM_INVALID.getMsg());
            JSONObject message = new JSONObject(r);
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        //12. 放行
        return chain.filter(exchange);
    }

    public List<String> getJwtExcludePath() {
        return jwtExcludePath;
    }

    public void setJwtExcludePath(List<String> jwtExcludePath) {
        this.jwtExcludePath = jwtExcludePath;
    }

    @Override
    public int getOrder() {
        return 1;
    }


}